<template>
  <div class="organization-page">
    <div class="arch-tree">
      <tree ref="business_tree" :props="business_props" folderIcon boundIcon @node-click="business_treeNodeClick" @operator-click="opeClick" lazy :loadFn="loadFn" :root='business_data' :drag-option='business_dragOption' edit
         @edit-name-valid="businessEidt" :default-text='"新生成接点"' :hover-color='"#f5f7fa"' :operator-offset-x='30' :operator-offset-y='-20' :highlight-color='"green"'>
        <div slot="right">
          <ul class="operator right" @mouseout="handleRightOperatorOut">
            <li @mouseenter="operatorRight.addMenu = true" @mouseleave="operatorRight.addMenu = false">添加<span class="arrow fr"></span>
              <ul v-show="operatorRight.addMenu" class="operator secondMenu">
                <!-- <li data-method="handleBortherAdd">添加同级节点</li> -->
                <li data-method="handleSingleAdd">添加子节点</li>
              </ul>
            </li>
            <!-- <li @mouseenter="operatorRight.moveMenu = true" @mouseleave="operatorRight.moveMenu = false">移动<span class="arrow fr"></span>
              <ul v-show="operatorRight.moveMenu" class="operator secondMenu">
                <li data-method="handleMoveUp">向上移动</li>
                <li data-method="handleMoveDown">向下移动</li>
              </ul>
            </li> -->
            <li data-method="handleDelete">删除</li>
          </ul>
        </div>
      </tree>
      <el-dialog title="节点信息" :visible.sync="addForm.visible" width="50%">
        <el-form :model="addForm" ref="addForm" label-width="100px">
          <el-form-item v-for="(name, index) in addForm.names" :label="'节点名'" :key="name.key" :prop="'names.' + index + '.value'" :rules="{ required: true, message: '节点名不能为空', trigger: 'blur' }">
            <el-input v-model="name.value" style="width:90%"></el-input>
            <span v-if="index !== 0" class="el-icon-minus" @click="handleRemoveNameInput(index)"></span>
          </el-form-item>
        </el-form>
        <!-- <div class="text-center">
          <span class="el-icon-plus" style="fontSize:20px;marginBottom:16px;" @click="handleNodeNameInput"></span>
        </div> -->
        <div class="text-center">
          <el-button class="saveButtom" type="primary" @click="handleAddNodeSubmit">确 定</el-button>
          <el-button class="saveButtom" @click="handleAddNodeCancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import Tree from "@/components/Tree";
  import Api from "@/server/tree";

  export default {
    components: {
      Tree: Tree
    },
    async mounted() {
      //一级树
      let getRootBus = await Api.getRootBus()
      this.business_data = getRootBus
    },
    data() {
      return {
        structure: {},
        isDirty: false,
        addForm: {
          flag: 0,
          visible: false,
          names: [{
            value: "",
            key: Date.now()
          }]
        },
        operatorRight: {
          addMenu: false,
          moveMenu: false
        },
        business_props: {
          name: "orgName",
          children: "children"
        },
        business_data: [{
          // orgName: 'aaa',
          // children: [
          //   {
          //     orgName: 'bbb'
          //   }
          // ]
        }],
        businessNode: null,
        businessAddList: [],
        businessBindList: [],
        business_high: false,
        business_dragOption: {
          draggable: false,
          highlight: true,
          style: {
            background: "#cff0ff",
            border: "1px solid #00b8ee",
            borderRadius: "4px"
          }
        },
        operatorBound: {
          width: 450,
        }
      };
    },
    methods: {
      //按需加载
      async loadFn(VN, resolve, reject) {
        let model = VN.model;
        let subBus = await Api.getSubBus({
          // id: model.id,
          pid: model.id,
          status: 1,
          // month: this.getMonth("organizationMonth")
        });
        resolve(subBus);
      },
      async handleAddNodeSubmit() {
        let isValid = await this.$refs.addForm
          .validate()
          .catch(e => console.log(e));
        if (!isValid) return;
        /**
         * this.addForm.flag
         *  0 ---- 添加子节点
         *  1 ==== 添加同级节点
         */
        let parentNode, params;
        const flag = this.addForm.flag;
        const isTree = this.businessNode.$parent.isTree;
        if (flag && isTree) {
          params = {
            level: 1,
          };
        } else {
          parentNode = flag ?
            this.businessNode.$parent.model :
            this.businessNode.model;
          // const orders = flag ? this.businessNode.model.orders : null;
          const {
            id: pid,
            orgName: parentSelfName,
            level: parentLevel
          } = parentNode;
          params = {
            // orders,
            status: 1,
            pid,
            parentSelfName,
            parentLevel,
            level: +parentLevel + 1
          };
        }

        params.orgName = this.addForm.names.map(item => {
          return item.value
        }).join(',')
        let resp = await Api.addBus(params);
        // TODO ERROR HANDLE
        if (this.isNull(resp)) {
          return this.$alert("已经存在同级同名节点");
        }
        if (this.isArray(resp)) {
          // 缓存新增节点
          this.businessAddList.push(...resp);
          // 重新刷新节点树
          if (flag && isTree) {
            this.business_data.push(...resp);
          } else {
            if (flag) {
              // 增加同级节点 - 且非根节点
              this.businessNode.$parent.addChild(...resp);
            } else {
              // 增加子节点
              this.businessNode.model.isHasSon = "1";
              this.businessNode.addChild(...resp);
            }
          }
          this.addForm.names = [{
            value: "",
            key: Date.now()
          }];
          this.addForm.visible = false;
        }
      },

      handleAddNodeCancel() {
        this.addForm.names = [{
          value: "",
          key: Date.now()
        }];
        this.addForm.visible = false;
      },
      handleRemoveNameInput(index) {
        this.addForm.names.splice(index, 1);
      },
      handleNodeNameInput() {
        this.addForm.names.push({
          value: "",
          key: Date.now()
        });
      },
      //更改节点名称
      async businessEidt(VN, resolve, reject) {
        let model = VN.model;
        let {
          id,
          pid,
          status,
          orgName: _orgName
        } = model;
        let orgName = VN.form._name;
        if (orgName !== _orgName) {
          let updateBusName = await Api.updateBusName({
            orgName,
            pid,
            status,
            id
          });
          console.log(updateBusName)
          if (this.isArray(updateBusName)) {
            resolve();
          } else {
            reject();
          }
        } else {
          resolve();
        }
      },
      business_treeClose() {
        this.$refs.organization_tree.doHide();
        this.$refs.business_tree.doHide();
      },
      async business_treeNodeClick(ev, addfunc, removeFunc, VN) {
        this.businessNode = VN;
        let type = ev.button ? "right" : "left";
        this.$refs.business_tree.doShow(type);
      },
      /**@augments
       * 0 -- business
       * 1 -- organization
       */
      opeClick(ev, addfunc, removeFunc, model) {
        let method = ev.target.getAttribute("data-method");
        this[method] && this[method](addfunc, removeFunc, model);
      },

      async handleBortherAdd() {
        this.addForm.flag = 1;
        this.addForm.visible = true;
        this.$refs.business_tree.doHide();
      },
      async handleSingleAdd() {
        this.addForm.flag = 0;
        this.addForm.visible = true;
        this.$refs.business_tree.doHide();
      },
      async _handleMove(to) {

        const model = this.businessNode.model;
        const isTree = this.businessNode.$parent.isTree;
        const params = {};
        // RootBus
        params.id = model.id;
        params.orgName = model.orgName;
        params.Order = to;
        // params.oldOrder = model.orders;
        if (!isTree) {
          params.pid = model.pid;
          // params.parentSelfName = model.parentSelfName;
        }
        // params.newOrder = +params.oldOrder + (to ? 1 : -1);
        let updateBusOrder = await Api.updateBusOrder(params);
        if (this.isArray(updateBusOrder)) {
          // 刷新节点树
          if (!isTree) {
            this.businessNode.$parent.model.children = updateBusOrder;
          } else {
            this.business_data = updateBusOrder;
          }
        }
      },
      async handleMoveUp() {
        this._handleMove(0);
      },
      async handleMoveDown() {
        this._handleMove(1);
      },
      async handleDelete() {
        let businessNode = this.businessNode;
        this.$confirm('注意：删除此部门会导致其下属所有子部门一并删除，此部门的员工将会丢失组织架构！', {
          // 消失前触发 阻塞消失
          beforeClose: async(action, instance, done) => {
            if (action === "cancel") {
              done();
            } else {
              let params;
              let isRootBus = businessNode.$parent.isTree;
              const id = businessNode.model.id;

              if (isRootBus) {
                params = {
                  id
                };
              } else {
                const {
                  // level,
                  id,
                  pid,
                  orgName,
                  status = 0,
                } = businessNode.model;
                params = {
                  id,
                  pid,
                  orgName,
                  status: 0,
                  // parentLevel: +level - 1
                };
              }
              let rootBus = this.business_data;

              if (isRootBus && rootBus.length === 1) {
                done();
                return this.$message("请勿删除最后一个根节点");
              }
              let delBus = await Api.delBus(params);
              // console.log(delBus,'---delBus',this.isNull(delBus),!delBus[0].status);
              // if (this.isNull(delBus)) {
              if (!delBus[0].status) {
                /**@augments
                 * 处理图标
                 * 决定刷新家那一级数据
                 */
                businessNode.removeChild(businessNode.model.id);
                if (!isRootBus) {
                  let $parent = businessNode.$parent,
                    model = $parent.model;
                  if (!model.children.length) {
                    model.isHasSon = "0";
                  }
                }
                done();
              }
            }
          }
        });
      },
      handleRightOperatorOver(ev) {},
      handleRightOperatorOut(ev) {},
    }
  };
</script>

<style lang="scss">
  .operator {
    width: 120px;
    .operator-title {
      padding: 10px 10px 4px 12px;
      height: 36px;
      line-height: 18px;
      border-bottom: 1px solid #ccc;
       :nth-child(1) {
        margin-right: 0px;
      }
      .triangle-facing-left {
        position: absolute;
        left: -6px;
        top: 18px;
        width: 12px;
        height: 12px;
        border-top: 2px solid #ebebeb;
        border-left: 2px solid #ebebeb;
        border-radius: 2px;
        -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
        background: #fff;
      }
      .close {
        position: absolute;
        right: 12px;
        top: 16px;
      }
    }
    .operator-list {
      max-height: 200px;
      overflow: auto;
      margin-top: 12px;
      li {
        position: relative;
        .unbind {
          position: absolute;
          top: 8px;
          right: 8px;
        }
      }
    }
    &.right {
      li {
        position: relative;
        padding: 0 8px 0 16px;
        height: 36px;
        line-height: 36px;
        .arrow {
          margin-top: 11px;
        }
        &:hover {
          background-color: #bcddf1;
        }
      }
      .secondMenu {
        position: absolute;
        top: -8px;
        left: 100%;
        background: #fff;
      }
    }
    &.left {
      width: 450px;
      li:nth-child(even) {
        background: #f5fcff;
      }
      li {
        padding: 4px 12px 8px;
        line-height: 20px;
        button {
          border: none;
        }
      }
    }
    border: 1px solid #ebebeb;
    border-radius: 3px;
    -webkit-transition: 0.2s;
    transition: 0.2s;
    box-shadow: 0 0 10px 0px #ccc;

  }
  .text-center{
    text-align: center;
  }
</style>
